import datetime
import sys

import requests
from bs4 import BeautifulSoup
import re

from wechat.wechat_push import wechat_push


def run():
    user_name = sys.argv[1]
    user_passwd = sys.argv[2]
    send_key = None
    if len(sys.argv) == 4:
        send_key = sys.argv[3]

    session = requests.session()
    session.headers.update({
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36"
        })
    # 1. 打开登录页面，返回的其实是一个xml，里面有登录需要的关键数据
    res = session.get('https://www.4ksj.com/member.php?mod=logging&action=login&infloat=yes&handlekey=login&inajax=1&ajaxtarget=fwin_content_login')

    xml_root = BeautifulSoup(res.text, 'lxml')
    form = xml_root.find('form', attrs={'name': "login"})

    # 2. 解析xml中的关键数据
    action = form.attrs['action']
    formhash = form.find('input', attrs={'name': "formhash"}).attrs['value']
    referer = form.find('input', attrs={'name': "referer"}).attrs['value']

    # 3. 发送Post请求登录
    login_url = f'https://www.4ksj.com/{action}&inajax=1'
    res = session.post(login_url, data={
        'formhash': formhash,
        'referer': referer,
        'username': user_name,
        'password': user_passwd,
        'questionid': '0',
        'answer': ''
        })

    # 4. 检测是否登录成功
    if res.text.find('欢迎您回来') == -1:
        print(res.text)
        print('登录失败')
        if send_key:
            wechat_push(send_key, f'【4K世界】登录失败', '')
        return

    print(user_name + ' 登录成功 ' + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))

    # 5. 获取当前K币数量
    kb_before = get_KB_num(session)
    print('当前K币数量：' + kb_before)

    # 6. 获取签到链接
    res = session.get('https://www.4ksj.com/qiandao.php')
    qiandao_page = BeautifulSoup(res.text, 'html.parser')
    sign_href_tag = qiandao_page.find('a', attrs={'class': 'btna'})
    sign_href = sign_href_tag.attrs['href']
    sign_url = f'https://www.4ksj.com/{sign_href}'

    # 7. 签到
    res = session.get(sign_url)
    sign_result = BeautifulSoup(res.text, 'html.parser')
    sign_msg = sign_result.find('div', id="messagetext").find('p')
    print(sign_msg.text)

    # 7. 获取当前K币数量
    kb_after = get_KB_num(session)
    print('签到后K币数量：' + kb_after)

    if send_key:
        wechat_push(send_key, f'【4K世界】{sign_msg.text}', f'【签到前】{kb_before} 【签到后】{kb_after}')


def get_KB_num(session):
    res = session.get('https://www.4ksj.com/home.php?mod=spacecp&ac=credit')
    user_page = BeautifulSoup(res.text, 'html.parser')
    KB = user_page.find('li', attrs={'class': ['xi1', 'cl']})
    ret = re.search(r'K币.*个', KB.text)
    return ret.group()


if __name__ == '__main__':
    if len(sys.argv) < 3:
        print("参数错误")
        exit()

    run()

